<template>
  <div style="height:6vh;padding:10px 20px;background-color:#fff;">
    <span style="line-height:60px;font-size:20px;">员工考勤</span>
    <el-button type="primary" style="float:right;margin-top:13px; margin-left: 12px" @click="addAttendance">添加考勤</el-button>
    <!--    <el-button type="primary" style="float:right;margin-top:13px;" @click="exportData">导出</el-button>-->
    <el-button type="primary" style="float:right;margin-top:13px; margin-left: 12px" @click="exportData">
      <el-icon>
        <Download/>
      </el-icon>
      <span>数据导出</span>
    </el-button>
  </div>
  <!--新增/编辑功能弹窗-->
  <el-dialog
      :title="dialogTitle"
      style="width: 1000px;padding:40px;"
      v-model="dialogVisible"
      :before-close="handleClose"
  >
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="部门">
            <el-select placeholder="请选择" v-model="saveAttendanceForm.did" >
              <el-option v-for="item in staffDepOptions"
                         :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="员工姓名">
            <el-input placeholder="请输入员工姓名" v-model="saveAttendanceForm.username"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="工作时间">
            <el-date-picker
                placeholder="请选择工作时间"
                v-model="saveAttendanceForm.wtime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上班时间">
            <el-date-picker
                placeholder="请选择上班时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetime"
                v-model="saveAttendanceForm.uptime"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="下班时间">
            <el-date-picker
                placeholder="请选择上班时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetime"
                v-model="saveAttendanceForm.downtime"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-select placeholder="请选择" v-model="saveAttendanceForm.status" >
              <el-option v-for="item in attendanceTypeArr"
                         :label="item.label" :value="item.value" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveStaffAttendance">保存</el-button>
    </template>
  </el-dialog>

  <!--搜索卡片-->
  <el-card style="margin: 18px;">
    <el-form :inline="true" style="margin-top: 15px;">
      <el-form-item style="margin-left: 20px">
        <el-date-picker
            placeholder="请选择日期"
            type="datetime"
            v-model="wtime"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-input placeholder="请输入姓名" style="width: 220px;" v-model="username"
                  @click="loadAttendance"></el-input>
      </el-form-item>

      <el-form-item>
        <el-select placeholder="请选择部门" style="width: 220px;" v-model="did">
          <el-option v-for="item in staffDepOptions" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadAttendance">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!--员工考勤列表框-->
  <el-card style="margin: 20px;">
    <el-table :data="staffListArr" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column type="index" label="序列号" width="80" align="center"></el-table-column>
      <el-table-column label="员工姓名" prop="username" align="center"></el-table-column>
      <el-table-column label="员工部门" prop="did" align="center"></el-table-column>
      <el-table-column label="工作日期" prop="wtime" align="center" ></el-table-column>
      <el-table-column label="上班时间" prop="uptime" align="center"></el-table-column>
      <el-table-column label="下班时间" prop="downtime" align="center"></el-table-column>
      <el-table-column label="状态" prop="status" :formatter="attendanceStatusFormatter" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="editUser(scope.row.id)">编辑</el-button>
          <el-button link type="primary" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br/>
    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-card>


  <!-- 导出资产单列表弹窗 -->
  <el-dialog title="导出员工考勤信息为excel表格--数据预览" v-model="dialogExcelVisible"
             :before-close="exportClose" width="80%">
    <el-table :data="staffExportArr" id="selectTable">
      <el-table-column label="员工姓名" prop="username" align="center"></el-table-column>
      <el-table-column label="员工部门" prop="did" align="center"></el-table-column>
      <el-table-column label="工作日期" prop="wtime" align="center"></el-table-column>
      <el-table-column label="上班时间" prop="uptime" align="center"></el-table-column>
      <el-table-column label="下班时间" prop="downtime" align="center"></el-table-column>
      <el-table-column label="状态" prop="status" :formatter="attendanceStatusFormatter"  align="center"></el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="exportClose">取 消</el-button>
      <el-button type="primary" @click="exportExcel">确 定 导 出</el-button>
    </template>
  </el-dialog>


</template>

<script setup>

import {computed, onMounted, ref} from "vue";
import qs from "qs";
import axios from "/src/api/axios";
import {ElMessage} from "element-plus";
//导出表格的库
import * as XLSX from "xlsx"
import {saveAs} from 'file-saver';
//创建导出员工出勤列表数据的方法
import htmlToExcel from "@/utils/htmlToExcel";

//定义变量控制弹窗是否出现
const dialogVisible = ref(false);
//定义变量用来控制弹窗的标题
const dialogTitle = ref('添加考勤');

//获取当前登录的用户信息
const user = ref(getUser());

//定义员工部门数组来维护员工所属部门的选项, 重置和查询这里
const staffDepOptions = ref([
  {name: '部门1', id: '1'},
  {name: '部门2', id: '2'},
  {name: '部门3', id: '3'},
  {name: '部门4', id: '4'}
]);

//======================高级查询相关的数据====================
//定义对象来保存用户查询的条件
const username = ref('');
const did = ref('');
const wtime = ref('');


//======================分页相关的数据====================
//后面修改成这样
const staffListArr = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const totals = ref(0);
//定义加载出勤列表的方法,及查询
const loadAttendance = () => {
  //组装参数
  const params = ref({
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    username: username.value,
    did: did.value,
    wtime: wtime.value
  });

  let data = qs.stringify(params.value)
  //给后端发送get请求，查询员工考勤全部数据，显示在页面，如果有查询条件，根据条件查，没有条件默认查全部数据
  axios.get('/attendance/page?'+data,{serviceName:'workService'}).then((response) => {//回调函数,处理响应数据
    totals.value = response.data.totals;
    staffListArr.value = response.data.data;
    console.log(staffListArr.value);
  })
}



const handleCurrentChange = (c) =>{
  currentPage.value = c;
  loadAttendance();
}
const handleSizeChange = (d) =>{
  pageSize.value = d;
  loadAttendance();
}


//定义变量保存弹窗表单新增或修改考勤数据
const saveAttendanceForm = ref({
  username: '', //员工姓名
  did: '',//部门
  wime: '', //工作日期
  uptime: '',//上班时间
  downtime: '',//下班时间
  status: '',  //考勤状态 迟到,早退,矿工,缺勤
});

//定义数组变量保存考勤部门,弹窗里的部门
/*const departmentTypeArr = ref([
  //每个部门
  {label: '部门1', value: '1'},
  {label: '部门2', value: '2'},
  {label: '部门3', value: '3'},
  {label: '部门4', value: '4'},
]);*/



//定义数组变量保存考勤类型,弹窗里的考勤类型
const attendanceTypeArr = ref([
  //迟到,早退,矿工,缺勤
  {label: '出勤', value: '10'},
  {label: '迟到', value: '20'},
  {label: '早退', value: '30'},
  {label: '缺勤', value: '40'},
]);



//对考勤状态显示内容进行文字转换
const attendanceStatusFormatter = (row,column,cellValue,index)=>{
  if(cellValue == 10){
    cellValue = '出勤';
  }else if(cellValue == 20){
    cellValue = '迟到';
  }else if(cellValue == 30){
    cellValue = '早退';
  }else if(cellValue == 40){
    cellValue = '缺勤';
  }
  return cellValue;
}

//处理弹窗关闭的方法 ok
const handleClose = () => {
  if (confirm('确认要关闭本窗口吗?')) {
    //用户确认关闭后,关闭弹窗
    dialogVisible.value = false;
    //清空已输入的表单数据
    saveAttendanceForm.value = {};
  }
}

/* 点击"新建考勤"按钮，出现弹窗+修改弹窗标题的方法 */
const addAttendance = () => {
  dialogTitle.value = '新建考勤';
  dialogVisible.value = true;
}




//定义方法获取员工姓名数据 ，根据选择的部门选择员工
const loadStaffDep = () => {
  //给后端发请求,查询员工的部门
  axios.get('/v1/department/list?',{serviceName:'departmentService'})
      .then(
          (response)=>{
            if(response.data.code == 200){
              staffDepOptions.value = response.data.data;
              console.log(staffDepOptions.value);
            }else{
              ElMessage.error(response.data.msg);
            }
          }
      )
}


//* 点击弹窗中的“保存员工出勤”按钮 => 新增+更新员工出勤 */
const saveStaffAttendance = () => {
  //将收集到的表单数据转为字符串格式
  // let data = qs.stringify(saveAttendanceForm.value);
  // console.log(data);
  //给后端发送post请求，保存员工考勤的数据  添加数据
    axios.post('/attendance/save',saveAttendanceForm.value,{serviceName:'workService'})
        .then((response)=>{
          if(response.data.code == 2000){
            ElMessage.success('保存成功!');
            //保存成功后,关闭弹窗
            dialogVisible.value = false;
            //清空已输入的表单数据
            saveAttendanceForm.value = {};
            loadAttendance();
          }else{
            ElMessage.error(response.data.msg);
          }
        })

}

//创建修改员工考勤列表的方法,传id
const editUser = (id) => {
  //修改弹窗标题
  dialogTitle.value = '编辑考勤';
  //让弹窗出现
  dialogVisible.value = true;
  //向后发送get请求查询，根据id查询用户信息并回显在弹窗表格
  axios.get('/attendance/select/'+id, {
    serviceName:'workService',
  }).then((response)=>{
    console.log(response.data.msg);
    if(response.data.code==2000){
      //3.将数据赋值给表单响应式变量
      saveAttendanceForm.value = response.data.data;

    }else{
      ElMessage.error(response.data.msg);
    }
  })

}


//创建删除员工考勤列表的方法
const deleteUser = (id) => {
    if(confirm('您确认要删除吗?')){
      axios.post('/attendance/delete/'+id,{},{serviceName:'workService'}).then((response)=>{
        if(response.data.code==2000){
          ElMessage.success('删除成功!');
          loadAttendance();
        }else{
          ElMessage.error(response.data.msg);
        }
      })
    }
}




//控制导出数据弹窗
const dialogExcelVisible = ref(false);
//关闭导出资产弹窗的方法
const exportClose = () => {
  if (confirm('是否要关闭本弹窗？')) {
    dialogExcelVisible.value = false;
  }
};
//点击<确定导出>按钮触发的方法
const exportExcel = () => {
  htmlToExcel.getExcel('#selectTable', '考勤表');
};
//点击搜索栏的<导出>按钮触发的方法
const exportData = () => {
  if (staffExportArr.value.length < 1) {
    ElMessage.warning('请选择要导出的内容！');
    return false;
  }
  dialogExcelVisible.value = true;
};
const staffExportArr = ref([]);
const handleSelectionChange = (val) => {
  staffExportArr.value = val;
};


//重置搜索
const resetSearch = () => {
  //清空之前的搜索内容
  username.value='';
  did.value='';
  wtime.value='';
  //重新加载所有的用户数据
  loadAttendance();
}

//页面一加载完毕,立即执行
onMounted(() => {
  loadAttendance();
  loadStaffDep();
})



</script>

<style scoped>
</style>